use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufRead};

pub fn converter(input: &str, tp: &str) -> String {
    // 读取并构建字符映射
    let char_maps = load_char_maps("TSCharacters.txt").unwrap_or_default();
    // 读取并构建短语映射
    let phrase_maps = load_phrase_maps("STPhrases.txt").unwrap_or_default();
    
    match tp {
        "s2t" => convert_text(input, &phrase_maps, &char_maps, true),
        "t2s" => convert_text(input, &phrase_maps, &char_maps, false),
        _ => input.to_string(),
    }
}

fn load_char_maps(filename: &str) -> io::Result<HashMap<char, char>> {
    let file = File::open(filename)?;
    let reader = io::BufReader::new(file);
    let mut map = HashMap::new();
    
    for line in reader.lines() {
        if let Ok(line) = line {
            let parts: Vec<&str> = line.split('\t').collect();
            if parts.len() == 2 {
                if let (Some(trad), Some(simp)) = (parts[0].chars().next(), parts[1].chars().next()) {
                    map.insert(trad, simp);
                }
            }
        }
    }
    Ok(map)
}

fn load_phrase_maps(filename: &str) -> io::Result<HashMap<String, String>> {
    let file = File::open(filename)?;
    let reader = io::BufReader::new(file);
    let mut map = HashMap::new();
    
    for line in reader.lines() {
        if let Ok(line) = line {
            let parts: Vec<&str> = line.split('\t').collect();
            if parts.len() == 2 {
                map.insert(parts[0].to_string(), parts[1].to_string());
            }
        }
    }
    Ok(map)
}

fn convert_text(input: &str, phrase_maps: &HashMap<String, String>, char_maps: &HashMap<char, char>, is_s2t: bool) -> String {
    // 首先尝试整个短语转换
    if is_s2t {
        if let Some(converted) = phrase_maps.iter()
            .find(|(k, _)| *k == input)
            .map(|(_, v)| v.clone()) {
            return converted;
        }
    } else {
        if let Some(converted) = phrase_maps.iter()
            .find(|(_, v)| *v == input)
            .map(|(k, _)| k.clone()) {
            return converted;
        }
    }

    // 如果没有找到对应的短语，则逐字转换
    input.chars().map(|c| {
        if is_s2t {
            // 简体转繁体
            if let Some(converted) = char_maps.iter()
                .find(|(_, &v)| v == c)
                .map(|(&k, _)| k) {
                converted
            } else {
                c
            }
        } else {
            // 繁体转简体
            char_maps.get(&c).copied().unwrap_or(c)
        }
    }).collect()
}

